package com.heima.comment.service.impl;

import com.heima.comment.service.HotCommentService;
import com.heima.model.comment.pojos.ApComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author feng js
 */
@Service
public class HotCommentServiceImpl implements HotCommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    @Async("taskExecutor")
    public void findHotComment(Long entryId, ApComment apComment) {
        Query query = Query.query(Criteria.where("entryId").is(entryId).and("flag").is(1)).with(Sort.by(Sort.Direction.DESC));
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);

        if (apComments != null && apComments.size() > 0) {
            ApComment lastApComment = apComments.get(apComments.size() - 1);
            if (lastApComment.getLikes() < apComment.getLikes()) {
                apComment.setFlag((short) 1);
                mongoTemplate.save(apComment);
                if (apComment.getLikes() >= 5) {
                    lastApComment.setFlag((short) 0);
                    mongoTemplate.save(lastApComment);
                }
            }
        } else {
            apComment.setFlag((short)1);
            mongoTemplate.save(apComment);
        }
    }
}
